package com.tbvtc.agriculturalcreditchainserver2025.utils.Pest;

import cn.hutool.core.bean.BeanUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tbvtc.agriculturalcreditchainserver2025.constant.SmsConstant;
import com.tbvtc.agriculturalcreditchainserver2025.pojo.pear.MainPestPear;
import com.tbvtc.agriculturalcreditchainserver2025.pojo.pear.PlantDiseasePredictionResult;
import com.tbvtc.agriculturalcreditchainserver2025.service.SmsService;
import com.tbvtc.agriculturalcreditchainserver2025.service.impl.IpfsServiceImpl;
import com.tbvtc.agriculturalcreditchainserver2025.constant.RedisConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.nio.file.*;
import java.io.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Component
public class ImageReceiverUtils {

    private static final Logger logger = LoggerFactory.getLogger(ImageReceiverUtils.class);
    @Resource
    private PestHttpUtils pestHttpUtils;
    @Resource
    private ObjectMapper objectMapper;
    @Resource(name = "TredisTemplate")
    private RedisTemplate redisTemplate;
    @Resource(name = "stringRedisTemplate")
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private PestReportUtils pestReportUtils;
    @Resource
    private IpfsServiceImpl ipfsService;
    @Autowired
    private SmsService smsService;
    // 主要保存目录
    private static String SAVE_DIR = PestConstant.imageFilePath;

    // 备用保存目录（临时目录）
    private static final String FALLBACK_DIR = System.getProperty("java.io.tmpdir") + "/captures/";

    // 日期格式化器，用于创建YYYY-MM-DD格式的目录
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    static {
        // 初始化根目录
        initializeSaveDirectory();
    }

    private static void initializeSaveDirectory() {
        // 优先尝试使用配置目录
        Path mainDir = Paths.get(SAVE_DIR);
        try {
            // 尝试创建根目录并测试写入
            Files.createDirectories(mainDir);
            // 测试权限
            Path testFile = mainDir.resolve("permission_test.tmp");
            Files.write(testFile, "test".getBytes(), StandardOpenOption.CREATE);
            Files.delete(testFile);
            logger.info("使用主保存根目录: {}", mainDir.toAbsolutePath());
            return;
        } catch (Exception e) {
            logger.warn("主目录不可用: {}", e.getMessage());
        }
        // 使用备用目录
        try {
            SAVE_DIR = FALLBACK_DIR;
            Path fallbackDir = Paths.get(SAVE_DIR);
            Files.createDirectories(fallbackDir);
            logger.info("使用备用保存根目录: {}", fallbackDir.toAbsolutePath());
        } catch (Exception e) {
            logger.error("无法创建备用目录: {}", e.getMessage());
            System.exit(1); // 严重错误，退出应用
        }
    }

    /**
     * 服务器接受树莓派发送来的图片
     *
     * @param file
     * @return
     */

//    @PostMapping(value = "/api/images/receive", consumes = "multipart/form-data")
//    public String receiveImage(@RequestParam("image") MultipartFile file) {
    public String receiveImage(String hash) {
        long startTime = System.currentTimeMillis();
        try {

            byte[] bytes = new RestTemplate().getForObject(PestConstant.ipfsURL + hash, byte[].class);
            //根据传进来的图片进行识别pestReportUtils
            String pearPestResult = pestHttpUtils.
                    uploadPearImage(bytes, PestConstant.fileName);
            //根据模型进行分析是否有病虫害
            PlantDiseasePredictionResult result =
                    objectMapper.readValue(pearPestResult, PlantDiseasePredictionResult.class);
            MainPestPear mainPestPear =
                    BeanUtil.copyProperties(result, MainPestPear.class);
            logger.error("图片识别结果: {}",
                    mainPestPear.getIs_healthy() ? "健康" : "有病害" + result.getMain_prediction()
                            .getClass_name_zh());
            //判断是否有锁
            if (!redisTemplate.hasKey(RedisConstant.PEST_LOCK)) {
                pestReportUtils.addPearPestReport(mainPestPear,hash);
                if (!mainPestPear.getIs_healthy()){
                    logger.error("发现病虫害，发送短信");
                    smsService.sendCode(SmsConstant.PHONE,SmsConstant.FARMNAME);
                    stringRedisTemplate.opsForValue().set(RedisConstant.PEST_IMAGE,hash,1,TimeUnit.DAYS);
                    redisTemplate.opsForValue().setIfAbsent(RedisConstant.PEST_LOCK,"lock",1,TimeUnit.DAYS);
                }
            }
        } catch (Exception e) {
            logger.error("处理失败: {}", e.getMessage());
            return "{\"status\":\"error\",\"message\":\"" + e.getMessage() + "\"}";
        } finally {
            long elapsed = System.currentTimeMillis() - startTime;
            logger.info("请求处理时间: {} ms\n{}", elapsed, "=".repeat(60));
        }
        return "{\"status\":\"success\"}";
    }

    // 文件名清理
    private String sanitizeFilename(String filename) {
        // 移除非法字符
        return filename.replaceAll("[\\\\/:*?\"<>|]", "_");
    }

    // 生成短文件名
    private String generateShortFilename(String original) {
        int dotIndex = original.lastIndexOf('.');
        String ext = dotIndex > 0 ? original.substring(dotIndex) : "";
        return "img_" + System.currentTimeMillis() + ext;
    }

    public void playMp3(String mp3FilePath) throws IOException {
        // 1. 读取MP3文件并转换为Base64编码
        String base64Mp3 = encodeMp3ToBase64(mp3FilePath);
        // 2. 构建请求参数
        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("mp3_base64", base64Mp3);
        // 3. 发送POST请求
        // 使用postForObject发送请求并接收响应
        restTemplate.postForObject(
                "http://192.168.178.104:5005/play-base64-mp3",
//                "http://39.98.75.146:17005/play-base64-mp3",
                requestBody,
                Map.class
        );
    }

    /**
     * 将MP3文件编码为Base64字符串
     */
    private String encodeMp3ToBase64(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists() || !file.isFile()) {
            throw new IllegalArgumentException("MP3文件不存在或不是有效文件：" + filePath);
        }
        // 读取文件内容
        byte[] fileBytes = new byte[(int) file.length()];
        try (FileInputStream fis = new FileInputStream(file)) {
            fis.read(fileBytes);
        }
        // 编码为Base64字符串
        return Base64.getEncoder().encodeToString(fileBytes);
    }


}
